/**
 * 主题工具函数 - 自动检测深浅色模式
 */

// 检测当前主题
export const getCurrentTheme = () => {
  // 检查系统主题偏好
  const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

  // 检查是否有主题设置覆盖系统偏好
  const htmlElement = document.documentElement
  const hasThemeClass = htmlElement.classList.contains('dark') || htmlElement.classList.contains('light')

  if (hasThemeClass) {
    return htmlElement.classList.contains('dark') ? 'dark' : 'light'
  }

  return prefersDark ? 'dark' : 'light'
}

// 获取主题对应的文字颜色
export const getTextColor = (theme = null) => {
  const currentTheme = theme || getCurrentTheme()
  return currentTheme === 'dark' ? '#ffffff' : '#000000'
}

// 获取主题对应的背景色
export const getBackgroundColor = (theme = null) => {
  const currentTheme = theme || getCurrentTheme()
  return currentTheme === 'dark' ? '#1a1a1a' : '#ffffff'
}

// 监听主题变化
export const watchThemeChange = (callback) => {
  if (!callback) return null

  // 监听系统主题变化
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  const handleThemeChange = () => callback(getCurrentTheme())

  if (mediaQuery.addEventListener) {
    mediaQuery.addEventListener('change', handleThemeChange)
  } else {
    // 兼容旧版浏览器
    mediaQuery.addListener(handleThemeChange)
  }

  // 监听DOM class 变化
  const observer = new MutationObserver(() => {
    callback(getCurrentTheme())
  })

  observer.observe(document.documentElement, {
    attributes: true,
    attributeFilter: ['class']
  })

  return {
    mediaQuery,
    handleThemeChange,
    observer
  }
}

// 清理主题监听器
export const cleanupThemeWatch = (watchers) => {
  if (!watchers) return

  const { mediaQuery, handleThemeChange, observer } = watchers

  if (mediaQuery) {
    if (mediaQuery.removeEventListener) {
      mediaQuery.removeEventListener('change', handleThemeChange)
    } else {
      mediaQuery.removeListener(handleThemeChange)
    }
  }

  if (observer) {
    observer.disconnect()
  }
}